<template>
  <view class="container">
    <view class="filter-section">
      <view class="date-range">
        <view class="date-picker">
          <text>开始日期:</text>
          <uni-datetime-picker type="date" v-model="startDate" @change="handleDateChange" />
        </view>
        <view class="date-picker">
          <text>结束日期:</text>
          <uni-datetime-picker type="date" v-model="endDate" @change="handleDateChange" />
        </view>
      </view>
      <button class="query-btn" @click="handleQuery">查询</button>
    </view>

    <view class="stats-section">
      <view class="stat-item">
        <text class="label">总工资:</text>
        <text class="value">¥{{ totalSalary }}</text>
      </view>
      <view class="stat-item">
        <text class="label">记录数:</text>
        <text class="value">{{ totalRecords }}</text>
      </view>
    </view>

    <view class="records-section">
      <view class="batch-actions" v-if="selectedRecords.length">
        <text>已选择 {{ selectedRecords.length }} 条记录</text>
        <button class="delete-btn" @click="handleBatchDelete">批量删除</button>
      </view>
      
      <scroll-view 
        scroll-y 
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        class="scroll-view"
      >
        <view class="record-list">
          <view v-for="record in records" :key="record.id" 
                class="record-item"
                :class="{ 
                  'selected': selectedRecords.includes(record.id),
                  'pending': record.status === 0,
                  'rejected': record.status === 2 // 添加驳回状态类
                }"
                @tap="handleRecordClick(record)"
                @longpress="handleLongPress(record)">
            <view class="record-date">{{ formatDate(record.createTime) }}</view>
            <view class="record-info">
              <view class="record-left">
                <text class="record-type">{{ getRecordTitle(record) }}</text>
                <text class="status-tag pending-tag" v-if="record.status === 0">待审核</text>
                <text class="status-tag rejected-tag" v-if="record.status === 2">已驳回</text> </view>
              <text class="record-amount">¥{{ record.totalAmount }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <uni-popup ref="detailPopup" type="center">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="title">记录详情</text>
          <text class="close" @click="closeDetailPopup">×</text>
        </view>
        <view class="popup-content" v-if="currentRecord">
          <view class="detail-item">
            <text class="label">日期:</text>
            <text class="value">{{ formatDate(currentRecord.createTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">类型:</text>
            <text class="value">{{ getRecordTypeText(currentRecord.type) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">金额:</text>
            <text class="value">¥{{ currentRecord.totalAmount }}</text>
          </view>
          <view class="detail-item" v-if="currentRecord.type === 1">
            <text class="label">单价:</text>
            <text class="value">¥{{ currentRecord.workItemPrice }}</text>
          </view>
          <view class="detail-item" v-if="currentRecord.type === 1">
            <text class="label">数量:</text>
            <text class="value">{{ currentRecord.quantity }}</text>
          </view>
          <view class="detail-item">
            <text class="label">备注:</text>
            <text class="value">{{ currentRecord.remark || '无' }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="delete-btn" @click="handleDelete">删除</button>
          <button class="close-btn" @click="closeDetailPopup">关闭</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import dayjs from 'dayjs'
import salary from '@/api/salary'

export default {
  data() {
    return {
      startDate: '',
      endDate: '',
      records: [
        // 示例数据，你可以移除或替换为真实数据
        { id: 1, createTime: '2025-06-24T10:00:00', totalAmount: 120, status: 0, workItemName: '工件A', name: '完成工件A', type: 1, workItemPrice: 10, quantity: 12, remark: '待审核测试' },
        { id: 2, createTime: '2025-06-23T15:30:00', totalAmount: 80, status: 1, workItemName: '工件B', name: '完成工件B', type: 2, remark: '已通过测试' },
        { id: 3, createTime: '2025-06-22T09:00:00', totalAmount: 50, status: 2, workItemName: '工件C', name: '完成工件C', type: 1, workItemPrice: 5, quantity: 10, remark: '驳回测试，数据不符' }, // 驳回示例
      ],
      totalSalary: 0,
      totalRecords: 0,
      selectedRecords: [],
      currentRecord: null,
      refreshing: false
    }
  },

  onLoad() {
    this.fetchRecords()
  },

  onShow() {
    // 确保页面回到前台时刷新数据
    this.fetchRecords()
  },

  methods: {
    async fetchRecords() {
      try {
        const params = {}
        if (this.startDate && this.endDate) {
          // 确保日期格式符合后端要求，通常是YYYY-MM-DD
          params.startDate = dayjs(this.startDate).format('YYYY-MM-DD')
          params.endDate = dayjs(this.endDate).format('YYYY-MM-DD')
        }

        const res = await salary.getSalaryStats(params)
        this.totalSalary = res.totalAmount || 0
        this.records = res.workRecords || []
        this.totalRecords = this.records.length
      } catch (error) {
        uni.showToast({
          title: '获取记录失败',
          icon: 'none'
        })
      } finally {
        // 如果是下拉刷新触发的，关闭刷新状态
        if (this.refreshing) {
          this.refreshing = false
          uni.stopPullDownRefresh()
        }
      }
    },

    handleDateChange() {
      // 日期变化时重置选中状态
      this.selectedRecords = []
    },

    async handleQuery() {
      if ((!this.startDate && this.endDate) || (this.startDate && !this.endDate)) {
        uni.showToast({
          title: '请同时选择开始和结束日期',
          icon: 'none'
        })
        return
      }

      if (this.startDate && this.endDate && dayjs(this.endDate).isBefore(this.startDate, 'day')) { // 比较日期时加上 'day' 单位
        uni.showToast({
          title: '结束日期不能早于开始日期',
          icon: 'none'
        })
        return
      }

      await this.fetchRecords()
    },

    handleRecordClick(record) {
      if (this.selectedRecords.length > 0) {
        // 批量选择模式
        this.toggleRecordSelection(record)
      } else {
        // 查看详情
        this.showRecordDetail(record)
      }
    },

    handleLongPress(record) {
      this.toggleRecordSelection(record)
    },

    toggleRecordSelection(record) {
      const index = this.selectedRecords.indexOf(record.id)
      if (index === -1) {
        this.selectedRecords.push(record.id)
      } else {
        this.selectedRecords.splice(index, 1)
      }
    },

    showRecordDetail(record) {
      this.currentRecord = record
      this.$refs.detailPopup.open()
    },

    closeDetailPopup() {
      this.$refs.detailPopup.close()
      this.currentRecord = null
    },

    async handleDelete() {
      if (!this.currentRecord) return

      try {
        await this.deleteRecords([this.currentRecord.id])
        this.closeDetailPopup()
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    },

    async handleBatchDelete() {
      if (!this.selectedRecords.length) return

      // 将选中的记录按类型分组
      const type1Records = []
      const type2Records = []
      
      // 遍历选中的记录ID，根据类型分组
      this.selectedRecords.forEach(id => {
        const record = this.records.find(r => r.id === id)
        if (record) {
          if (record.type === 1) {
            type1Records.push(record.id)
          } else if (record.type === 2) {
            type2Records.push(record.id)
          }
        }
      })

      // 如果没有有效记录，直接返回
      if (type1Records.length === 0 && type2Records.length === 0) {
        uni.showToast({
          title: '没有可删除的记录',
          icon: 'none'
        })
        return
      }

      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的 ${this.selectedRecords.length} 条记录吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 分别删除不同类型的记录
              const deletePromises = []
              
              // 删除第一类工作记录
              if (type1Records.length > 0) {
                console.log('删除类型1记录:', type1Records)
                deletePromises.push(salary.batchDeleteType1(type1Records))
              }
              
              // 删除第二类工作记录
              if (type2Records.length > 0) {
                console.log('删除类型2记录:', type2Records)
                deletePromises.push(salary.batchDeleteType2(type2Records))
              }
              
              // 等待所有删除操作完成
              await Promise.all(deletePromises)
              
              // 清空选中状态
              this.selectedRecords = []
              // 重新获取记录列表
              await this.fetchRecords()
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } catch (error) {
              console.error('批量删除失败:', error)
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    async deleteRecords(ids) {
      if (!ids.length) return
      
      const record = this.records.find(r => r.id === ids[0])
      if (!record) return
      
      // 根据记录类型调用对应的删除接口
      if (record.type === 1) {
        await salary.deleteType1Record(record.id)
      } else if (record.type === 2) {
        await salary.deleteType2Record(record.id)
      }
      
      await this.fetchRecords()
    },

    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm') // 修改为更详细的时间显示，方便查看创建时间
    },

    // 格式化工作记录显示
    getRecordTypeText(type) {
      return type === 1 ? '计件工资' : '特殊工资'
    },

    getRecordTitle(record) {
      let title = record.type === 1 ? 
        `${record.workItemName} x ${record.quantity}` : 
        record.workItemName;
      
      // 添加驳回状态前缀
      if (record.status === 2) {
        title = `[已驳回] ${title}`;
      }
      return title;
    },

    // 修改下拉刷新方法
    async onRefresh() {
      if (this.refreshing) return // 如果正在刷新，直接返回
      this.refreshing = true
      await this.fetchRecords()
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
}

.filter-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.date-range {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.date-picker {
  flex: 1;
  margin: 0 10rpx;
}

.query-btn {
  width: 100%;
  background-color: #007AFF;
  color: #fff;
}

.stats-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-item .label {
  color: #666;
  font-size: 28rpx;
}

.stat-item .value {
  color: #007AFF;
  font-size: 32rpx;
  font-weight: bold;
}

.records-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  height: calc(100vh - 280rpx);
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx;
  margin-bottom: 20rpx;
}

.delete-btn {
  background-color: #FF3B30;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 6rpx;
}

.record-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #fff;
  transition: all 0.3s ease;
  border-left: 4rpx solid transparent; /* 默认透明边框 */
}

.record-item.selected {
  background-color: #e6f7ff; /* 选中时的背景色更亮 */
  border: 2rpx solid #007aff; /* 选中时的边框 */
}

.record-item.pending {
  background-color: #fff7e6; /* 待审核的背景色 */
  border-left: 8rpx solid #ff9900; /* 待审核的左边框更粗 */
}

.record-item.rejected {
  background-color: #fff0f0; /* 驳回的背景色，更柔和的红色 */
  border-left: 8rpx solid #dc3545; /* 驳回的左边框，鲜明的红色 */
}


.record-date {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.record-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-left {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.record-type {
  font-size: 32rpx;
  color: #333;
}

.record-amount {
  font-size: 32rpx;
  color: #007AFF;
  font-weight: bold;
}

.status-tag {
  font-size: 24rpx;
  color: #fff; /* 状态标签文字白色 */
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  border: none; /* 移除边框，使用背景色填充 */
}

.pending-tag {
  background-color: #ff9900; /* 待审核标签背景色 */
}

.rejected-tag {
  background-color: #dc3545; /* 驳回标签背景色 */
}

.detail-popup {
  background-color: #fff;
  border-radius: 10rpx;
  width: 600rpx;
}

.popup-header {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.popup-header .title {
  font-size: 32rpx;
  font-weight: bold;
}

.popup-header .close {
  font-size: 40rpx;
  color: #666;
}

.popup-content {
  padding: 20rpx;
}

.detail-item {
  margin-bottom: 20rpx;
}

.detail-item .label {
  color: #666;
  margin-right: 20rpx;
}

.popup-footer {
  padding: 20rpx;
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.close-btn {
  background-color: #f5f5f5;
  color: #333;
}

.scroll-view {
  height: 100%;
}
</style>